package main

import (
	"GuessNumberGame01/core"
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var (
	game core.GuessNum
)

const (
	MAXCOUNT  = 10
	ORIGMINNUM = 1
	ORIGMAXNUM = 100
)

func Init() {
	if 0 == game.GetCurrentGuessTime() {
		numGen := core.NewNumberGenerator(ORIGMINNUM, ORIGMAXNUM)
		game = core.NewGame(MAXCOUNT, numGen)
		//game.SetMinNumber(ORIGMINNUM)
		//game.SetMaxNumber(ORIGMAXNUM)
		//game.GenerateTargetNumber()
	}
}

func main() {
	input := bufio.NewScanner(os.Stdin)

	// 是否继续游戏的状态
	continueState := 'y'

	game.CountInit()
	// 主循环，1次循环为1个完整的游戏过程
	for  {
		switch continueState {
		case 'y':
			Init()
			// 输入数字
			fmt.Printf("请输入在(%d~%d)中猜测的一个数值(第%d次):\n", game.GetSmallest(), game.GetBiggest(), game.GetCurrentGuessTime()+1)
			//var num int
			//fmt.Scanln(&num)
			if input.Scan() {
				numText := input.Text()
				num, err := strconv.ParseInt(numText, 10, 64)
				if err != nil {
					fmt.Println("输入的内容不是数字，请重新输入")
					continue
				}

				if int(num) < game.GetSmallest() ||
					int(num) > game.GetBiggest() {
					fmt.Println("输入的数字不在正确的范围内，请重新输入")
					continue
				}
				game.SetGuess(int(num))
				//猜数次数增加
				game.CountIncrease()
				// 判断游戏是否失败
				if true == game.IsGameLost() {
					fmt.Printf("很遗憾没有猜出来，答案是%d\n", game.GetNumber())
					break
				}

				// 判断猜数是否正确
				if game.GetNumber() == game.GetGuess() {
					fmt.Printf("恭喜你猜出了%d，猜测次数为%d\n", game.GetNumber(), game.GetCurrentGuessTime())
				} else if game.GetNumber() < game.GetGuess() {
					game.SetMaxNumber(game.GetGuess() - 1)
					fmt.Printf("猜大了，")
					continue
				} else {
					game.SetMinNumber(game.GetGuess() + 1)
					fmt.Printf("猜小了，")
					continue
				}

			}
		case 'o':
		default:
		}
		// 询问是否继续游戏
		fmt.Println("是否继续游戏？(y/n)")
		if input.Scan() {
			if 'y' == strings.ToLower(input.Text())[0] {
				continueState = 'y'
			}  else if 'n' == strings.ToLower(input.Text())[0] {
				break
			}  else {
				continueState = 'o'
			}
			game.CountInit()
		}
	}
}
